package com.zhr.tea.view.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.GsonBuilder;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.zhr.tea.R;
import com.zhr.tea.api.ShouyeService;
import com.zhr.tea.entity.shouye.Banner;
import com.zhr.tea.entity.shouye.BodyCentent;
import com.zhr.tea.entity.shouye.BodyEnter;
import com.zhr.tea.entity.shouye.End;
import com.zhr.tea.utils.IsLogin;
import com.zhr.tea.view.activity.BannerWebActivity;
import com.zhr.tea.view.activity.ChaQuanActivity;
import com.zhr.tea.view.activity.ChayiActivity;
import com.zhr.tea.view.activity.ProductActivity;
import com.zhr.tea.view.activity.RegestActivity;
import com.zhr.tea.view.activity.ShouyeCenterActivity;
import com.zhr.tea.view.activity.ShouyeJingcaiActivity;
import com.zhr.tea.view.adapter.ShouyeAdapter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.finalteam.okhttpfinal.BaseHttpRequestCallback;
import cn.finalteam.okhttpfinal.HttpRequest;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * A simple {@link Fragment} subclass.
 */
public class ShouYeFragment extends Fragment implements ShouyeAdapter.BannerListen, ShouyeAdapter.RecycleClickListener {
    @BindView(R.id.xlv)
    XRecyclerView xlv;
    private List<Banner.AdColumnListBean> banner = new ArrayList<>();
    private List<End.ContentBean> end = new ArrayList<>();
    private List<BodyCentent.ContentBean.ThemeListBean> themeListBeen = new ArrayList<>();
    private List<BodyCentent.ContentBean.ChannelListBean> channelListBeen = new ArrayList<>();
    private List<BodyCentent.ContentBean.BenefitSaleBean.GoodsListBean> benefitSaleBeen = new ArrayList<>();
    private BodyEnter bodyEnter;
    private ShouyeAdapter adapter;
    private ShouyeService shouyeService;
    private ShouyeService bannerService;
    private int page = 0;
    private String pageId = "";

    public ShouYeFragment() {
        // Required empty public constructor
    }

    public static ShouYeFragment newInstance() {

        Bundle args = new Bundle();

        ShouYeFragment fragment = new ShouYeFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_shou_ye, container, false);
        ButterKnife.bind(this, view);
        initView();
        initData();
        return view;
    }

    private void initData() {

        shouyeService.getBodyData().enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                String json = null;
                try {
                    json = response.body().string();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                String js = json.substring(json.indexOf("(") + 1, json.indexOf(")"));
                BodyCentent bc = JSONObject.parseObject(js, BodyCentent.class);
                themeListBeen.addAll(bc.getContent().getThemeList());
                channelListBeen.addAll(bc.getContent().getChannelList());
                if (bc.getContent().getBenefitSale().size() != 0) {
                    benefitSaleBeen.addAll(bc.getContent().getBenefitSale().get(0).getGoodsList());
                }
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });


        getEndData();
        bannerService.getBannerData().enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                String json = null;
                try {
                    json = response.body().string();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                String js = json.substring(json.indexOf("(") + 1, json.lastIndexOf(")"));
                Banner b = JSONObject.parseObject(js, Banner.class);
                banner.addAll(b.getAdColumnList());
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });
        xlv.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                page = 0;
                getEndData();
            }

            @Override
            public void onLoadMore() {
                if (page <= 140) {
                    page += 20;
                    getEndData();
                }
            }
        });
    }

    private void getEndData() {
        shouyeService.getEndData(page).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                String json = null;
                try {
                    json = response.body().string();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                String js = json.substring(json.indexOf("(") + 1, json.lastIndexOf(")"));
                End e = JSONObject.parseObject(js, End.class);
                end.addAll(e.getContent());
                adapter.notifyDataSetChanged();
                xlv.loadMoreComplete();
                xlv.refreshComplete();
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });
    }

    private void initView() {
        xlv.setLayoutManager(new LinearLayoutManager(getContext()));
        adapter = new ShouyeAdapter(banner, benefitSaleBeen, channelListBeen, getContext(), end, themeListBeen, this);
        adapter.setOnitemClickListener(this);
        xlv.setAdapter(adapter);
        Retrofit retrofit = new Retrofit.Builder().baseUrl(ShouyeService.BASE_URL).addConverterFactory(GsonConverterFactory.create(new GsonBuilder().create())).build();
        shouyeService = retrofit.create(ShouyeService.class);
        Retrofit bannerRetrofit = new Retrofit.Builder().baseUrl(ShouyeService.BASEBANNER_URL).addConverterFactory(GsonConverterFactory.create(new GsonBuilder().create())).build();
        bannerService = bannerRetrofit.create(ShouyeService.class);
    }

    Intent intent;

    @Override
    public void bannerListen(int position) {
        intent = new Intent(getContext(), BannerWebActivity.class);
        intent.putExtra("url", banner.get(position).getShareUrl());
        startActivity(intent);
    }

    @Override
    public void textType1Listen() {
        intent = new Intent(getContext(), BannerWebActivity.class);
        intent.putExtra("url", "http://picture.teapaopao.com/common/FreePlaytwo/index.html?phoneNum=");
        startActivity(intent);
    }

    @Override
    public void textType2Listen() {
        intent = new Intent(getContext(), BannerWebActivity.class);
        intent.putExtra("url", "http://picture.teapaopao.com/yuanchaPlatform/coupon/index.html?phoneNum=18272162916");
        startActivity(intent);
    }

    @Override
    public void textType3Listen() {
        intent = new Intent(getContext(), ChayiActivity.class);
        startActivity(intent);
    }

    @Override
    public void textType4Listen() {
        intent = new Intent(getContext(), BannerWebActivity.class);
        intent.putExtra("url", "http://picture.teapaopao.com/common/zhongchou/outInfo.html?phoneNum=");
        startActivity(intent);
    }

    @Override
    public void textType5Listen() {
        intent=new Intent(getContext(), ChaQuanActivity.class);
        startActivity(intent);
    }

    @Override
    public void tvType4Listen(int position) {
        pageId = themeListBeen.get(position).getSubThemeList().get(0).getPara().substring(themeListBeen.get(position).getSubThemeList().get(0).getPara().indexOf("=") + 1);
        HttpRequest.get("http://120.55.137.143:54321/service/teabubble/ad?methods=searchSecondPage&jsonp=true&pageId=" + pageId + "&_=1478164525936&jsonp_method=callbackSearchHomePage", new BaseHttpRequestCallback<String>() {
            @Override
            protected void onSuccess(String s) {
                super.onSuccess(s);
                String s1 = s.substring(s.indexOf("(") + 1, s.lastIndexOf(")"));
                BodyEnter be = JSONObject.parseObject(s1, BodyEnter.class);
                bodyEnter = be;
                intent = new Intent(getContext(), ShouyeCenterActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("cen", bodyEnter);
                intent.putExtras(bundle);
                startActivity(intent);
            }

            @Override
            public void onFailure(int errorCode, String msg) {
                super.onFailure(errorCode, msg);
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }
        });
    }

    @Override
    public void tvType4Listen1(int position) {
        pageId = themeListBeen.get(position).getSubThemeList().get(1).getPara().substring(themeListBeen.get(position).getSubThemeList().get(1).getPara().indexOf("=") + 1);
        if (pageId.length() < 3) {
            HttpRequest.get("http://120.55.137.143:54321/service/teabubble/ad?methods=searchSecondPage&jsonp=true&pageId=" + pageId + "&_=1478164525936&jsonp_method=callbackSearchHomePage", new BaseHttpRequestCallback<String>() {
                @Override
                protected void onSuccess(String s) {
                    super.onSuccess(s);
                    String s1 = s.substring(s.indexOf("(") + 1, s.lastIndexOf(")"));
                    BodyEnter be = JSONObject.parseObject(s1, BodyEnter.class);
                    bodyEnter = be;
                    intent = new Intent(getContext(), ShouyeCenterActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("cen", bodyEnter);
                    intent.putExtras(bundle);
                    startActivity(intent);
                }

                @Override
                public void onFailure(int errorCode, String msg) {
                    super.onFailure(errorCode, msg);
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                }
            });
        } else {
            intent = new Intent(getContext(), ProductActivity.class);
            intent.putExtra("id", Integer.valueOf(pageId));
            startActivity(intent);
        }
    }

    @Override
    public void tvType4Listen2(int position) {
        pageId = themeListBeen.get(position).getSubThemeList().get(2).getPara().substring(themeListBeen.get(position).getSubThemeList().get(2).getPara().indexOf("=") + 1);
        if (pageId.length() < 3) {
        HttpRequest.get("http://120.55.137.143:54321/service/teabubble/ad?methods=searchSecondPage&jsonp=true&pageId=" + pageId + "&_=1478164525936&jsonp_method=callbackSearchHomePage", new BaseHttpRequestCallback<String>() {
            @Override
            protected void onSuccess(String s) {
                super.onSuccess(s);
                String s1 = s.substring(s.indexOf("(") + 1, s.lastIndexOf(")"));
                BodyEnter be = JSONObject.parseObject(s1, BodyEnter.class);
                bodyEnter = be;
                intent = new Intent(getContext(), ShouyeCenterActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("cen", bodyEnter);
                intent.putExtras(bundle);
                startActivity(intent);
            }

            @Override
            public void onFailure(int errorCode, String msg) {
                super.onFailure(errorCode, msg);
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }
        });}else {
            intent = new Intent(getContext(), ProductActivity.class);
            intent.putExtra("id", Integer.valueOf(pageId));
            startActivity(intent);
        }
    }

    @Override
    public void tvType5Listen(int position) {
        pageId = themeListBeen.get(position).getSubThemeList().get(0).getPara().substring(themeListBeen.get(position).getSubThemeList().get(0).getPara().indexOf("=") + 1);
        HttpRequest.get("http://120.55.137.143:54321/service/teabubble/ad?methods=searchSecondPage&jsonp=true&pageId=" + pageId + "&_=1478164525936&jsonp_method=callbackSearchHomePage", new BaseHttpRequestCallback<String>() {
            @Override
            protected void onSuccess(String s) {
                super.onSuccess(s);
                String s1 = s.substring(s.indexOf("(") + 1, s.lastIndexOf(")"));
                BodyEnter be = JSONObject.parseObject(s1, BodyEnter.class);
                bodyEnter = be;
                intent = new Intent(getContext(), ShouyeCenterActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("cen", bodyEnter);
                intent.putExtras(bundle);
                startActivity(intent);
            }

            @Override
            public void onFailure(int errorCode, String msg) {
                super.onFailure(errorCode, msg);
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }
        });
    }

    @Override
    public void tvType5Listen1(int position) {
        pageId = themeListBeen.get(position).getSubThemeList().get(1).getPara().substring(themeListBeen.get(position).getSubThemeList().get(1).getPara().indexOf("=") + 1);
        if (pageId.length() < 3) {
            HttpRequest.get("http://120.55.137.143:54321/service/teabubble/ad?methods=searchSecondPage&jsonp=true&pageId=" + pageId + "&_=1478164525936&jsonp_method=callbackSearchHomePage", new BaseHttpRequestCallback<String>() {
                @Override
                protected void onSuccess(String s) {
                    super.onSuccess(s);
                    String s1 = s.substring(s.indexOf("(") + 1, s.lastIndexOf(")"));
                    BodyEnter be = JSONObject.parseObject(s1, BodyEnter.class);
                    bodyEnter = be;
                    intent = new Intent(getContext(), ShouyeCenterActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("cen", bodyEnter);
                    intent.putExtras(bundle);
                    startActivity(intent);
                }

                @Override
                public void onFailure(int errorCode, String msg) {
                    super.onFailure(errorCode, msg);
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                }
            });
        } else {
            intent = new Intent(getContext(), ProductActivity.class);
            intent.putExtra("id", Integer.valueOf(pageId));
            startActivity(intent);
        }
    }

    @Override
    public void tvType5Listen2(int position) {
        pageId = themeListBeen.get(position).getSubThemeList().get(2).getPara().substring(themeListBeen.get(position).getSubThemeList().get(2).getPara().indexOf("=") + 1);
        if (pageId.length() < 3) {
            HttpRequest.get("http://120.55.137.143:54321/service/teabubble/ad?methods=searchSecondPage&jsonp=true&pageId=" + pageId + "&_=1478164525936&jsonp_method=callbackSearchHomePage", new BaseHttpRequestCallback<String>() {
                @Override
                protected void onSuccess(String s) {
                    super.onSuccess(s);
                    String s1 = s.substring(s.indexOf("(") + 1, s.lastIndexOf(")"));
                    BodyEnter be = JSONObject.parseObject(s1, BodyEnter.class);
                    bodyEnter = be;
                    intent = new Intent(getContext(), ShouyeCenterActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("cen", bodyEnter);
                    intent.putExtras(bundle);
                    startActivity(intent);
                }

                @Override
                public void onFailure(int errorCode, String msg) {
                    super.onFailure(errorCode, msg);
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                }
            });}else {
            intent = new Intent(getContext(), ProductActivity.class);
            intent.putExtra("id", Integer.valueOf(pageId));
            startActivity(intent);
        }
    }

    @Override
    public void tvType5Listen3(int position) {
        pageId = themeListBeen.get(position).getSubThemeList().get(3).getPara().substring(themeListBeen.get(position).getSubThemeList().get(3).getPara().indexOf("=") + 1);
        if (pageId.length() < 3) {
            HttpRequest.get("http://120.55.137.143:54321/service/teabubble/ad?methods=searchSecondPage&jsonp=true&pageId=" + pageId + "&_=1478164525936&jsonp_method=callbackSearchHomePage", new BaseHttpRequestCallback<String>() {
                @Override
                protected void onSuccess(String s) {
                    super.onSuccess(s);
                    String s1 = s.substring(s.indexOf("(") + 1, s.lastIndexOf(")"));
                    BodyEnter be = JSONObject.parseObject(s1, BodyEnter.class);
                    bodyEnter = be;
                    intent = new Intent(getContext(), ShouyeCenterActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("cen", bodyEnter);
                    intent.putExtras(bundle);
                    startActivity(intent);
                }

                @Override
                public void onFailure(int errorCode, String msg) {
                    super.onFailure(errorCode, msg);
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                }
            });}else {
            intent = new Intent(getContext(), ProductActivity.class);
            intent.putExtra("id", Integer.valueOf(pageId));
            startActivity(intent);
        }
    }

    @Override
    public void tvType6Listen() {
            intent=new Intent(getContext(),ShouyeJingcaiActivity.class);
    startActivity(intent);
    }

    @Override
    public void ivCarListen(int position) {
        if (IsLogin.user != null) {
//            CarUtils.addCar();
        } else {
            intent = new Intent(getContext(), RegestActivity.class);
            startActivity(intent);
        }

    }

    @Override
    public void itemClick(View view, int code) {
        intent = new Intent(getContext(), ProductActivity.class);
        intent.putExtra("id", code);
        startActivity(intent);
    }
}
